<?php
function connectDB()
{
    $host = "localhost";
    $user = "alexey";
    $pass = "alex_lazer";
    $link_id = mysql_connect($host, $user, $pass);
    mysql_select_db('fly', $link_id) or die(mysql_error());
    mysql_query("SET NAMES 'utf8'");
    mysql_query("SET CHARACTER SET 'utf8'");
    return $link_id;
}

function init()
{
    session_start();
    if ($_SESSION['id'] != '') {
        return true;
    } else if (isset($_COOKIE['login']) && isset($_COOKIE['pass'])) {
        if (loginUser($_COOKIE['login'], $_COOKIE['pass'])) {
            return true;
        }
    } else {
        return false;
    }
}

function display()
{
    if (init()) {
        echo "style='display: block'";
    } else echo "style='display: none'";
}

function getResponseComments($start, $end, $nid)
{
    connectDB();
    $resultSet = mysql_query("SELECT
                                     responses.id AS id,
                                     likes,
                                     dislikes,
                                     quote,
                                     content,
                                     date,
                                     time,
                                     nick AS author,
                                     registered,
                                     messages,
                                     address,
                                     image,
                                     email
                               FROM responses
    INNER JOIN users ON responses.userid = users.id
     WHERE responses.newsid = " . mysql_real_escape_string($nid) . " ORDER BY date LIMIT " . mysql_real_escape_string($start - 1) . "," . mysql_real_escape_string($end)) or die(mysql_error());
    return $resultSet;
}

function getResponseImages($rid)
{
    connectDB();
    $resultSet = mysql_query("SELECT path FROM respimages WHERE respid=" . $rid) or die(mysql_error());
    return $resultSet;

}

function countPages($newsId)
{
    connectDB();
    $resultSet = mysql_query("SELECT COUNT(id) AS rec FROM responses WHERE newsid = '" . mysql_real_escape_string($newsId) . "'");
    $row = mysql_fetch_assoc($resultSet);
    return ceil($row['rec'] / 20);
}

function getResponseComment($id)
{
    connectDB();
    $resultSet = mysql_query("SELECT id, content FROM responses WHERE id = " . mysql_real_escape_string($id));
    return $resultSet;
}

function getFormattedTime()
{
    $microtime = microtime();
    $microtime = str_replace(" ", "", $microtime);
    $microtime = str_replace(".", "", $microtime);
    return $microtime;

}

function getAvatarSrc($id)
{
    connectDB();
    $resultSet = mysql_query("SELECT image FROM users WHERE id=" . $id);
    $row = mysql_fetch_assoc($resultSet);
    return $row['image'];

}

function startTransaction()
{
    mysql_query("SET AUTOCOMMIT=0");
    mysql_query("BEGIN");
}

function commitTransaction()
{
    mysql_query("COMMIT");
}

function rollbackTransaction()
{
    mysql_query("ROLLBACK");
}

function getLastComments($topicId)
{
    connectDB();

    startTransaction();

    $resultSet = mysql_query("SELECT users.nick AS author,
                                       content,
                                       date,
                                       time
                                FROM topicmessages
                                     INNER JOIN users ON topicmessages.userid = users.id
                                WHERE topicid = '" . $topicId . "'
                                ORDER BY date, time DESC
                                LIMIT 3

");
    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function getTopics($userId)
{
    connectDB();
    startTransaction();
    $topicSet = mysql_query("SELECT sections.header AS section,
                                topics.id as id,
                                topics.msg as msg,
                                users.nick AS author,
                                topics.header AS header,
                                topics.content AS content,
                                topics.date AS date,
                                topics.time AS time,
                                groups.header AS agroup,
                                usrtopic.read AS uread
                         FROM usrtopic
                            INNER JOIN topics ON usrtopic.tid = topics.id
                            INNER JOIN sections ON topics.sectionid = sections.id
                            INNER JOIN users ON topics.authorid = users.id
                            INNER JOIN groups ON topics.groupid = groups.id

                         WHERE usrtopic.uid = '" . $userId . "'

                         ORDER BY topics.sectionid AND usrtopic.read DESC

") or die(mysql_error());


    if ($topicSet) {
        commitTransaction();
        return $topicSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getTextPart($text, $symbols)
{
    return substr($text, 0, $symbols) . "...";
}

function countTopicMessages($topicId)
{
    connectDB();
    startTransaction();

    $topicSet = mysql_query("SELECT count(id) AS cmsg FROM topicmessages WHERE topicid='" . mysql_real_escape_string($topicId) . "'");
    $topic = mysql_fetch_assoc($topicSet);

    if ($topicSet) {
        commitTransaction();
        return $topic['cmsg'];
    } else {
        rollbackTransaction();
        return 0;
    }
}

function pagesFromMessages($messages)
{
    $pages = ceil($messages / 20);
    return $pages;
}

function getStat($userId)
{

    connectDB();
    startTransaction();

    $userSet = mysql_query("SELECT messages, registered, email, nick, firstname, lastname, groups.header AS groups
                                FROM users
                                    INNER JOIN usrgroup ON users.id = usrgroup.userid
                                    INNER JOIN groups ON usrgroup.groupid = groups.id
                                WHERE users.id = '" . mysql_real_escape_string($userId) . "'");

    if ($userSet) {
        commitTransaction();
        return $userSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function getUserGroups()
{
    connectDB();
    startTransaction();

    $userGroupsSet = mysql_query("SELECT header, groups.id AS id
                                        FROM groups
                                            INNER JOIN usrgroup ON groups.id = usrgroup.groupid
                                        WHERE usrgroup.userid='" . mysql_real_escape_string($_SESSION['id']) . "'
                                        ORDER BY groups.id");

    if ($userGroupsSet) {
        commitTransaction();
        return $userGroupsSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function countGroupMembers($groupId)
{
    connectDB();
    startTransaction();

    $userGroupsSet = mysql_query("SELECT COUNT(userid) AS users
                                        FROM usrgroup
                                        WHERE groupid='" . mysql_real_escape_string($groupId) . "'");

    if ($userGroupsSet) {
        commitTransaction();
        $users = mysql_fetch_assoc($userGroupsSet);
        return $users['users'];
    } else {
        rollbackTransaction();
        return 0;
    }
}

function getOtherGroups()
{
    connectDB();
    startTransaction();

    $otherGroupsSet = mysql_query("SELECT header, id
                                        FROM groups
                                        WHERE id != 1
                                        ORDER BY id");

    if ($otherGroupsSet) {
        commitTransaction();
        return $otherGroupsSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getUserInfo($id)
{
    connectDB();
    startTransaction();

    $userInfoSet = mysql_query("SELECT * FROM users WHERE id='" . mysql_real_escape_string($id) . "'");

    if ($userInfoSet) {
        commitTransaction();
        return mysql_fetch_assoc($userInfoSet);
    } else {
        rollbackTransaction();
        return null;
    }

}

function getUserVisibility()
{
    connectDB();
    startTransaction();

    $visResultSet = mysql_query("SELECT visible FROM users WHERE id='" . $_SESSION['id'] . "'");

    if ($visResultSet) {
        commitTransaction();
        $visRow = mysql_fetch_assoc($visResultSet);
        $vis = $visRow['visible'];
        return $vis;
    } else {
        rollbackTransaction();
        return 0;
    }

}

function getGalleryVisibility()
{
    connectDB();
    startTransaction();

    $visResultSet = mysql_query("SELECT galvis FROM users WHERE id='" . $_SESSION['id'] . "'");

    if ($visResultSet) {
        commitTransaction();
        $visRow = mysql_fetch_assoc($visResultSet);
        $vis = $visRow['galvis'];
        return $vis;
    } else {
        rollbackTransaction();
        return 0;
    }

}

function isWaitingForDelete()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT count(id) AS del FROM deleteusers WHERE userid='" . $_SESSION['id'] . "'");

    if ($resultSet) {
        commitTransaction();
        $resRow = mysql_fetch_assoc($resultSet);
        return $resRow['del'];
    } else {
        rollbackTransaction();
        return 0;
    }
}

function getUserGroup($id)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT max(groups.rights) AS rights
                              FROM groups
                              INNER JOIN usrgroup ON groups.id = usrgroup.groupid
                              INNER JOIN users ON usrgroup.userid = users.id
                              WHERE users.id='" . mysql_real_escape_string($id) . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        $resRow = mysql_fetch_assoc($resultSet);
        return $resRow['rights'];
    } else {
        rollbackTransaction();
        return 0;
    }
}

function getUsersGallery($id)
{
    connectDB();
    startTransaction();
    $usersGalleryRights = getUserGroup($_SESSION['id']);

    $resultSet = mysql_query("SELECT
                                    gallery.like,
                                    gallery.id,
                                    gallery.dislike,
                                    gallery.path,
                                    gallery.date,
                                    gallery.header,
                                    gallery.comment,
                                    gallery.time
                              FROM gallery
                              INNER JOIN gallerygroups ON gallery.id = gallerygroups.galid
                              INNER JOIN groups ON gallerygroups.groupid = groups.id
                              WHERE groups.rights <= '" . $usersGalleryRights . "'
                                AND
                                    gallery.userid = '" . mysql_real_escape_string($id) . "'
                              ORDER BY gallery.date, gallery.time DESC") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getSectionsByUserId()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                  topics.id,
                                  users.nick AS author,
                                  topics.header,
                                  topics.content,
                                  topics.date,
                                  topics.time,
                                  sections.header AS section,
                                  groups.header AS tgroup
                              FROM topics
                              INNER JOIN groups ON topics.groupid = groups.id
                              INNER JOIN usrgroup ON groups.id = usrgroup.groupid
                              INNER JOIN sections ON topics.sectionid = sections.id
                              INNER JOIN users ON topics.authorid = users.id
                              WHERE
                                    usrgroup.userid='" . $_SESSION['id'] . "'
                              ORDER BY sections.id") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}


function getTopic($id)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                topics.id,
                                topics.header,
                                topics.content,
                                topics.date,
                                topics.time,
                                users.nick AS author
                              FROM topics
                                 INNER JOIN groups ON topics.groupid = groups.id
                                 INNER JOIN usrgroup ON groups.id = usrgroup.groupid
                                 INNER JOIN users ON topics.authorid = users.id
                                 WHERE
                                        usrgroup.userid='" . $_SESSION['id'] . "'
                                    AND
                                        topics.id = '" . $id . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function getTopicComments($start, $end, $topicId)
{
    connectDB();

    startTransaction();

    $resultSet = mysql_query("SELECT
                                    users.id AS uid,
                                    users.nick AS author,
                                    users.registered AS registered,
                                    users.messages AS msg,
                                    users.email AS email,
                                    topicmessages.id,
                                    users.image AS img,
                                    content,
                                    date,
                                    time,
                                    likes,
                                    dislikes,
                                    quote
                                FROM topicmessages
                                     INNER JOIN users ON topicmessages.userid = users.id
                                WHERE topicid = '" . $topicId . "'
                                ORDER BY date, time
                                LIMIT " . mysql_real_escape_string($start - 1) . "," . mysql_real_escape_string($end)) or die(mysql_error());
    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function getTopicComment($commentId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT id, content FROM topicmessages WHERE id = " . mysql_real_escape_string($commentId));

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getTopicCommentImages($commentId)
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("SELECT path FROM topicimages WHERE topicmsgid=" . $commentId) or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function isSubscribedToTopic($topicId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT id
                              FROM usrtopic
                              WHERE
                                      tid='" . $topicId . "'
                                   AND
                                      uid='" . $_SESSION['id'] . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if (mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }

}

function getDialogs()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    dialogs.id,
                                    users.nick AS user,
                                    dialogs.read AS uread,
                                    getteruserid AS getter,
                                    senderuserid AS setter
                              FROM dialogs
                              INNER JOIN users ON if(senderuserid='" . $_SESSION['id'] . "', dialogs.getteruserid, dialogs.senderuserid) = users.id
                              WHERE
                                        dialogs.senderuserid='" . $_SESSION['id'] . "'
                                   OR
                                        dialogs.getteruserid='" . $_SESSION['id'] . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getDialogLastMsgInfo($dialogId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    date,
                                    time
                              FROM messages
                              WHERE
                                    dialogid='" . $dialogId . "'
                              ORDER BY date, time DESC
                              LIMIT 1") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function countDialogMessages($dialogId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    COUNT(id) AS msg
                              FROM messages
                              WHERE
                                    dialogid='" . $dialogId . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        $resultRow = mysql_fetch_assoc($resultSet);
        return $resultRow['msg'];
    } else {
        rollbackTransaction();
        return 0;
    }
}

function isConversationMember()
{

    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    id
                              FROM dialogs
                              WHERE
                                        senderuserid='" . $_SESSION['id'] . "'
                                    OR
                                        getteruserid='" . $_SESSION['id'] . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if (mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }
}

function getConversation($dialogId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    date,
                                    messages.id,
                                    time,
                                    users.id AS uid,
                                    content,
                                    users.nick AS author
                              FROM messages
                              INNER JOIN users ON messages.senderuserid = users.id
                              WHERE
                                    dialogid='" . $dialogId . "'
                              ORDER BY date, time asc") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getDialogPartner($dialogId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    users.nick AS partner
                              FROM dialogs
                              INNER JOIN users ON if(senderuserid='" . $_SESSION['id'] . "', dialogs.getteruserid, dialogs.senderuserid) = users.id
                              WHERE
                                    dialogs.id='" . $dialogId . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if ($partnerRow = mysql_fetch_assoc($resultSet)) {
            echo $partnerRow['partner'];
        }
    } else {
        rollbackTransaction();
    }
}

function checkIfDialogRead($dialogId)
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("UPDATE dialogs SET dialogs.read = '1'
                              WHERE
                                        id = '" . $dialogId . "'
                                    AND
                                        getteruserid = '" . $_SESSION['id'] . "'
                                    AND
                                        dialogs.read = '0'") or die(mysql_error());


    if ($resultSet) {
        commitTransaction();
    } else {
        rollbackTransaction();
    }
}

function getLastGalleryImages()
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("SELECT
                                    path,
                                    gallery.id,
                                    users.nick AS author,
                                    gallery.date,
                                    gallery.time
                              FROM gallerygroups
                              INNER JOIN groups ON gallerygroups.groupid = groups.id
                              INNER JOIN gallery ON gallerygroups.galid = gallery.id
                              INNER JOIN users ON gallerygroups.userid = users.id
                              WHERE
                                    groups.header = 'Base'
                              ORDER BY
                                    gallery.date DESC, gallery.time DESC
                              LIMIT 20") or die(mysql_error());


    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getAllGalleryImages()
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("SELECT
                                    path,
                                    gallery.id,
                                    gallery.header,
                                    gallery.comment,
                                    users.nick AS author,
                                    gallery.date,
                                    gallery.time
                              FROM gallerygroups
                              INNER JOIN groups ON gallerygroups.groupid = groups.id
                              INNER JOIN gallery ON gallerygroups.galid = gallery.id
                              INNER JOIN users ON gallerygroups.userid = users.id
                              WHERE
                                    groups.header = 'Base'
                              ORDER BY
                                    gallery.date DESC, gallery.time DESC") or die(mysql_error());


    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getGalleryImg($imageId)
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("SELECT
                                    gallery.path,
                                    gallery.date,
                                    gallery.time,
                                    gallery.header,
                                    gallery.comment,
                                    gallery.like AS likes,
                                    gallery.dislike AS dislikes,
                                    gallery.id,
                                    users.nick AS author
                              FROM gallerygroups
                              INNER JOIN groups ON gallerygroups.groupid = groups.id
                              INNER JOIN gallery ON gallerygroups.galid = gallery.id
                              INNER JOIN users ON gallery.userid = users.id
                              WHERE
                                        groups.header = 'Base'
                                    AND
                                        gallery.id = '" . $imageId . "'") or die(mysql_error());


    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getGalleryImgComments($start, $end, $imageId)
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("SELECT
                                    users.id AS uid,
                                    galcomments.id,
                                    date,
                                    time,
                                    content,
                                    likes,
                                    dislikes,
                                    quote,
                                    users.nick AS author,
                                    users.image AS img,
                                    users.registered,
                                    users.messages AS msg,
                                    users.email
                              FROM galcomments
                              INNER JOIN users ON galcomments.authorid = users.id
                              WHERE
                                   galcomments.galid = '" . $imageId . "'
                              ORDER BY
                                   date, time ASC
                              LIMIT " . mysql_real_escape_string($start - 1) . "," . mysql_real_escape_string($end)) or die(mysql_error());
    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function countGalleryImageComments($imageId)
{
    connectDB();
    startTransaction();

    $topicSet = mysql_query("SELECT count(id) AS cmsg FROM galcomments WHERE topicid='" . mysql_real_escape_string($imageId) . "'");
    $topic = mysql_fetch_assoc($topicSet);

    if ($topicSet) {
        commitTransaction();
        return $topic['cmsg'];
    } else {
        rollbackTransaction();
        return 0;
    }
}

function getGalleryComment($commentId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT id, content FROM galcomments WHERE id = " . mysql_real_escape_string($commentId));

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getLastFlies()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    flies.id,
                                    likes,
                                    dislikes,
                                    users.nick AS author,
                                    flyimages.path,
                                    legend,
                                    header,
                                    date,
                                    time
                              FROM flies
                              INNER JOIN users ON flies.authorid = users.id
                              INNER JOIN flyimages ON flies.mimg = flyimages.id
                              ORDER BY flies.date DESC, flies.time DESC
                              LIMIT 20") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getAllFlies()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    flies.id,
                                    likes,
                                    dislikes,
                                    users.nick AS author,
                                    flyimages.path,
                                    legend,
                                    header,
                                    date,
                                    time
                              FROM flies
                              INNER JOIN users ON flies.authorid = users.id
                              INNER JOIN flyimages ON flies.mimg = flyimages.id
                              ORDER BY flies.date DESC, flies.time DESC") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function countFlyComments($flyId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    COUNT(id) AS comments
                              FROM flycomments
                              WHERE flyid='" . $flyId . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return $row['comments'];
        } else {
            return 0;
        }
    } else {
        rollbackTransaction();
        return 0;
    }
}

function getFlyById($flyid)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    flies.id,
                                    likes,
                                    dislikes,
                                    users.nick AS author,
                                    flyimages.path,
                                    legend,
                                    header,
                                    flyimages.id AS mid,
                                    date,
                                    time
                              FROM flies
                              INNER JOIN users ON flies.authorid = users.id
                              INNER JOIN flyimages ON flies.mimg = flyimages.id
                              WHERE
                                    flies.id = '" . $flyid . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getFlyImages($flyId, $mainImgId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    path
                              FROM flyimages
                              WHERE
                                       flyid = '" . $flyId . "'
                                   AND
                                       id <> '" . $mainImgId . "'");

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getFlyComments($start, $end, $flyId)
{
    connectDB();
    startTransaction();
    $resultSet = mysql_query("SELECT
                                    flycomments.id,
                                    date,
                                    time,
                                    content,
                                    likes,
                                    dislikes,
                                    quote,
                                    users.nick AS author,
                                    users.image AS img,
                                    users.registered,
                                    users.messages AS msg,
                                    users.email
                              FROM flycomments
                              INNER JOIN users ON flycomments.userid = users.id
                              WHERE
                                   flycomments.flyid = '" . $flyId . "'
                              ORDER BY
                                   date, time ASC
                              LIMIT " . mysql_real_escape_string($start - 1) . "," . mysql_real_escape_string($end)) or die(mysql_error());
    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getFlyComment($commentId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT id, content FROM flycomments WHERE id = " . mysql_real_escape_string($commentId));

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function encryptString($login, $password)
{
    $tmpLogin = hash("tiger192,3", $login);
    $tmpConnector = hash("gost", "theFlyNet");
    $tmpPassword = hash("haval224,3", $password);
    $encryptedString = hash("snefru256", $tmpLogin . $tmpConnector . $tmpPassword);
    return $encryptedString;
}

function loginUser($login, $password)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT id FROM users WHERE nick='" . mysql_real_escape_string($login) . "' AND password='" . mysql_real_escape_string(encryptString($login, $password)) . "'");

    if ($row = mysql_fetch_assoc($resultSet)) {
        commitTransaction();
        session_start();
        $_SESSION['id'] = $row['id'];
        return true;
    } else {
        return false;
    }

}

function getLastNews()
{
    connectDB();
    startTransaction();


    $resultSet = mysql_query("SELECT
                                    news.id,
                                    header,
                                    content,
                                    date,
                                    time,
                                    path
                              FROM
                                    news
                              LEFT JOIN
                                    newsimages ON news.id = newsimages.newsid
                              WHERE
                                    newsimages.main = '1'
                              ORDER
                                    BY date DESC, time DESC
                              LIMIT 6") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getRandomSizeText($start, $end, $fullText)
{
    mt_srand();
    $length = mt_rand($start, $end);

    if (strlen($fullText) < $length) {
        $length = strlen($fullText);
    }
    return substr($fullText, 0, $length) . "..";
}

function getAllNews()
{
    connectDB();
    startTransaction();


    $resultSet = mysql_query("SELECT
                                    id,
                                    header,
                                    content,
                                    date,
                                    time
                              FROM
                                    news
                              ORDER
                                    BY date DESC, time DESC") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function getNewsImages($newsId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    path
                              FROM
                                    newsimages
                              WHERE
                                        newsid = '" . mysql_real_escape_string($newsId) . "'
                                    AND
                                        main = '0' ") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function checkTopicRead($topicId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("UPDATE usrtopic SET usrtopic.read = '1' WHERE tid='" . $topicId . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }

}

function checkDialogCreated($userId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    id
                              FROM
                                    dialogs
                              WHERE
                                            (dialogs.senderuserid = '" . mysql_real_escape_string($userId) . "'
                                        AND
                                            dialogs.getteruserid = '" . mysql_real_escape_string($_SESSION['id']) . "')
                                    OR
                                            (dialogs.senderuserid = '" . mysql_real_escape_string($_SESSION['id']) . "'
                                        AND
                                            dialogs.getteruserid = '" . mysql_real_escape_string($userId) . "')") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return $row['id'];
        } else {
            return 0;
        }
    } else {
        rollbackTransaction();
        return 0;
    }


}

function createDialog($userId)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("INSERT INTO
                                     dialogs(senderuserid, getteruserid)
                              VALUES
                                     ('" . $_SESSION['id'] . "',
                                     '" . mysql_real_escape_string($userId) . "')   ") or die(mysql_error());

    $newDialogId = mysql_insert_id();

    if ($resultSet) {
        commitTransaction();
        return $newDialogId;
    } else {
        rollbackTransaction();
        return 0;
    }
}

function searchUsers($userName)
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query(" SELECT
                                     id,
                                     nick,
                                     email,
                                     rating,
                                     messages
                               FROM
                                     users
                               WHERE
                                        nick LIKE '%" . mysql_real_escape_string($userName) . "%'
                                     AND
                                        id <> '" . $_SESSION['id'] . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function increaseUsersMessages()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("UPDATE users SET messages = messages + 1 WHERE id = '" . $_SESSION['id'] . "'") or die(mysql_error());
    if ($resultSet) {
        commitTransaction();
    } else {
        rollbackTransaction();
    }

}

function checkUserMail($mail)
{
    connectDb();
    startTransaction();

    $resultSet = mysql_query("SELECT id, nick FROM users WHERE email = '" . trim(mysql_real_escape_string($mail)) . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return $row;
        } else {
            return null;
        }
    } else {
        rollbackTransaction();
        return null;
    }
}

function isLiked($content, $contentId)
{
    connectDB();
    startTransaction();

    $query = "";

    switch ($content) {
        case "r":
            $query = "SELECT id FROM likes WHERE indicator = 'r' AND contentid = '" . $contentId . "'";
            break;
        case "t":
            $query = "SELECT id FROM likes WHERE indicator = 't' AND contentid = '" . $contentId . "'";
            break;
        case "i":
            $query = "SELECT id FROM likes WHERE indicator = 'i' AND contentid = '" . $contentId . "'";
            break;
        case "g":
            $query = "SELECT id FROM likes WHERE indicator = 'g' AND contentid = '" . $contentId . "'";
            break;
        case "f":
            $query = "SELECT id FROM likes WHERE indicator = 'f' AND contentid = '" . $contentId . "'";
            break;
        case "c":
            $query = "SELECT id FROM likes WHERE indicator = 'c' AND contentid = '" . $contentId . "'";
            break;
    }

    $resultSet = mysql_query($query);

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }
}

function isDisiked($content, $contentId)
{
    connectDB();
    startTransaction();

    $query = "";

    switch ($content) {
        case "r":
            $query = "SELECT id FROM dislikes WHERE indicator = 'r' AND contentid = '" . $contentId . "'";
            break;
        case "t":
            $query = "SELECT id FROM dislikes WHERE indicator = 't' AND contentid = '" . $contentId . "'";
            break;
        case "i":
            $query = "SELECT id FROM dislikes WHERE indicator = 'i' AND contentid = '" . $contentId . "'";
            break;
        case "g":
            $query = "SELECT id FROM dislikes WHERE indicator = 'g' AND contentid = '" . $contentId . "'";
            break;
        case "f":
            $query = "SELECT id FROM dislikes WHERE indicator = 'f' AND contentid = '" . $contentId . "'";
            break;
        case "c":
            $query = "SELECT id FROM dislikes WHERE indicator = 'c' AND contentid = '" . $contentId . "'";
            break;
    }

    $resultSet = mysql_query($query);

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }
}

function isSpammed($content, $contentId)
{
    connectDB();
    startTransaction();

    $query = "";

    $resultSet = null;

    switch ($content) {
        case "r":
            $query = "SELECT id FROM respspam WHERE respid = '" . $contentId . "' AND userid = '" . $_SESSION['id'] . "'";
            break;
        case "t":
            $query = "SELECT id FROM topicspam WHERE topicmsgid = '" . $contentId . "' AND userid = '" . $_SESSION['id'] . "'";
            break;
        case "g":
            $query = "SELECT id FROM galspam WHERE galid = '" . $contentId . "' AND userid = '" . $_SESSION['id'] . "'";
            break;
        case "c":
            $query = "SELECT id FROM flyspam WHERE flycommentid = '" . $contentId . "' AND userid = '" . $_SESSION['id'] . "'";
            break;
    }

    if ($query != "") {
        $resultSet = mysql_query($query);
    }

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }
}

function getSections()
{
    connectDB();
    startTransaction();

    $resultSet = mysql_query("SELECT id, header FROM sections") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        return $resultSet;
    } else {
        rollbackTransaction();
        return null;
    }
}

function canSeeTopic($topicId)
{
    connectDb();
    startTransaction();

    $resultSet = mysql_query("SELECT
                                    usrgroup.id
                              FROM usrgroup
                              INNER JOIN groups ON usrgroup.groupid = groups.id
                              INNER JOIN topics ON groups.id = topics.groupid
                              WHERE
                                    usrgroup.userid = '" . $_SESSION['id'] . "'
                              AND
                                    topics.id = '" . mysql_real_escape_string($topicId) . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }
}

function isWaitingForGroup($groupId)
{
    connectDb();
    startTransaction();

    $resultSet = mysql_query("SELECT id FROM entergroup
                              WHERE userid = '" . $_SESSION['id'] . "'
                              AND
                                    groupid = '" . mysql_real_escape_string($groupId) . "'") or die(mysql_error());

    if ($resultSet) {
        commitTransaction();
        if ($row = mysql_fetch_assoc($resultSet)) {
            return true;
        } else {
            return false;
        }
    } else {
        rollbackTransaction();
        return false;
    }
}

function redirect($url)
{
    echo "<script language='JavaScript'>
        location.href = '" . $url . "'
    </script>";
//    header("Location: " . $url);
}

function generatePassword($length)
{
    $chars = 'abdefhiknrstyzABDEFGHKNQRSTYZ23456789';
    $numChars = strlen($chars);
    $string = '';
    for ($i = 0; $i < $length; $i++) {
        $string .= substr($chars, rand(1, $numChars) - 1, 1);
    }
    return $string;
}

function getTextWithAcronym($text, $length)
{
    return "<acronym title='" . $text . "'>" . substr($text, 0, $length) . "</acronym>";
}

function getLocalTimeStamp()
{
    date_default_timezone_get("Europe/Minsk");
    return getdate()[0];
}

function f_Date($timeStamp)
{
    date_default_timezone_set('Europe/Minsk');
    return date("Y-m-d", $timeStamp);
}

function f_Time($timeStamp)
{
    date_default_timezone_set('Europe/Minsk');
    return date("H:i:s", $timeStamp);
}